//
//  FCPTabBarTemplate.swift
//  flutter_carplay
//
//  Created by Oğuzhan Atalay on 21.08.2021.
//

import CarPlay

@available(iOS 14.0, *)
class FCPTabBarTemplate: NSObject {
  private(set) var elementId: String
  private var title: String?
  private var templates: [CPTemplate]
  private var objcTemplates: [BaseTabBarTemplate]
  
  init(obj: [String : Any]) {
    self.elementId = obj["_elementId"] as! String
    self.title = obj["title"] as? String
    self.objcTemplates = (obj["templates"] as! Array<[String: Any]>).map {
        SwitchTemplate(obj: $0).get
    }
    self.templates = self.objcTemplates.map {
      $0.get
    }
  }
  
  var get: CPTabBarTemplate {
    let tabBarTemplate = CPTabBarTemplate.init(templates: templates)
    tabBarTemplate.tabTitle = title
    tabBarTemplate.delegate = self
    return tabBarTemplate
  }
  
  public func getTemplates() -> [BaseTabBarTemplate] {
    return self.objcTemplates
  }
    
  public func getListTemplates() -> [FCPListTemplate] {
    return self.objcTemplates.filter {
      $0 is FCPListTemplate
    }.map {
      $0 as! FCPListTemplate
    }
  }
    
  var getElementId: String {
    return elementId
  }
}

@available(iOS 14.0, *)
class SwitchTemplate{
    var obj : [String : Any]
    init(obj: [String : Any]) {
        self.obj = obj
    }
    
    var get: BaseTabBarTemplate {
        let type = obj["templateType"] as! String
        var template: BaseTabBarTemplate!
        switch type {
        case String(describing: FCPGridTemplate.self):
            template = FCPGridTemplate(obj: obj)
            break
        case String(describing: FCPListTemplate.self):
            template = FCPListTemplate(obj: obj, templateType: FCPListTemplateTypes.PART_OF_GRID_TEMPLATE)
            break
        default:
            break
        }
        return template ?? FCPListTemplate(obj: obj, templateType: FCPListTemplateTypes.PART_OF_GRID_TEMPLATE);
    }
    
}

@available(iOS 14.0, *)
extension FCPTabBarTemplate: FCPRootTemplate { }

@available(iOS 14.0, *)
extension FCPTabBarTemplate: CPTabBarTemplateDelegate {
    /**
     The user has selected one of the tabs in the tab bar template, bringing the selected template to the foreground.
     */
    public func tabBarTemplate(_ tabBarTemplate: CPTabBarTemplate, didSelect selectedTemplate: CPTemplate){
        let index = templates.firstIndex(where: { (e) -> Bool in
            return selectedTemplate.isEqual(e)
        })
        let tap = objcTemplates[index!];
        DispatchQueue.main.async {
            FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.tabBarTemplate, data: ["elementId": tap.elementId!])
        }
    }
}
